package cn.com.connext.scrm.service.mapper;

import cn.com.connext.scrm.domain.master.*;
import cn.com.connext.scrm.repository.master.*;
import cn.com.connext.scrm.service.dto.NoteDTO;
import cn.com.connext.scrm.utils.RedisUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public abstract class NoteMapperDecorator implements NoteMapper {

    @Autowired
    @Qualifier("delegate")
    private NoteMapper delegate;

    @Autowired
    private NoteLikesRepository noteLikesRepository;

    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    private BrowseRecordRepository browseRecordRepository;

    @Autowired
    private NoteCollectionRepository noteCollectionRepository;

    @Autowired
    private MemberRepository memberRepository;

    @Autowired
    private ActivityRepository activityRepository;

//    @Autowired
//    private StudentRepository studentRepository;

    @Autowired
    private TeacherRepository teacherRepository;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private DWAUserInfoRepository dwaUserInfoRepository;

    private final static Object REDIS_LOCK = new Object();
    private final static Object REDIS_LOCK2 = new Object();
    private final static Object REDIS_LOCK3 = new Object();

    private NoteDTO getDtoById(Note note) {
        NoteDTO noteDTO = delegate.toDto(note);
        //点赞数
        Integer totalLikes = 0;
        //评论数
        Integer totalComments = 0;
        Integer totalCollection = 0;
        //浏览量
        Integer totalBrowseRecords = 0;
        if (StringUtils.isNotEmpty(noteDTO.getId())) {
            String id = noteDTO.getId();
            totalLikes = noteLikesRepository.countAllByNoteId(id);
            totalComments = commentRepository.countAllByNoteId(id);
            totalBrowseRecords = browseRecordRepository.countAllByNoteId(id);
            totalCollection = noteCollectionRepository.countAllByNoteId(id);
        }
        noteDTO.setTotalLikes(totalLikes);
        noteDTO.setTotalComments(totalComments);
        noteDTO.setTotalBrowseRecords(totalBrowseRecords);
        noteDTO.setTotalCollection(totalCollection);
        //帖子图片url集合
        if (StringUtils.isNotEmpty(note.getImgUrl())) {
            List<String> list_imgUrl = Arrays.asList(StringUtils.split(note.getImgUrl(), ","));
            noteDTO.setImgUrlList(list_imgUrl);
        }
        //活动标签
        if (StringUtils.isNotEmpty(note.getActivityId())) {
            Activity activity=activityRepository.findOne(note.getActivityId());
            noteDTO.setActivity(activity);
        }
        //发帖人昵称、头像、标签
        if (StringUtils.isNotEmpty(note.getUserId())) {
            Member member = memberRepository.findOneByUnionId(note.getUserId());
            if (null != member) {
                noteDTO.setNickName(member.getNickName());
                noteDTO.setHeadImgUrl(member.getHeadImgUrl());
                if (StringUtils.isNotEmpty(member.getMobile())) {
                    String mobile = member.getMobile();
                    JSONArray tagsArray = new JSONArray();
//                        tagsList.add("官方认证");
                    if (null != member.getOfficialCertification() && member.getOfficialCertification() == true) {
                        JSONObject tag = new JSONObject();
                        tag.put("kind", 2);
                        tag.put("text", "官方认证");
                        tagsArray.add(tag);
                    } else {
                        List<String> teacherMobiles = getTeacherMobileList();
                        if (teacherMobiles.contains(mobile)) {
//                        ///打上官方认证的标签
//                        tagsList.add("DWA老师");
                            JSONObject tag = new JSONObject();
                            tag.put("kind", 1);
                            tag.put("text", "DWA导师");
                            tagsArray.add(tag);
                        } else {
                            List<DwaUserInfo> dwaUserInfos = dwaUserInfoRepository.findByUnionIdOrderByLessonLevelDesc(note.getUserId());
                            if (null != dwaUserInfos && dwaUserInfos.size() > 0) {
                                //dwa学员标签
                                DwaUserInfo dwaUserInfo = dwaUserInfos.get(0);
                                if (StringUtils.isNotEmpty(dwaUserInfo.getLessonLevel())) {
                                    String level = dwaUserInfo.getLessonLevel();
                                    JSONObject tag = new JSONObject();
                                    tag.put("kind", 0);
                                    if ("LEVEL1".equals(level)) {
                                        tag.put("text", "DWA L1");
                                    } else if ("LEVEL2".equals(level)) {
                                        tag.put("text", "DWA L2");
                                    } else if ("LEVEL3".equals(level)) {
                                        tag.put("text", "DWA L3");
                                    } else {
                                        tag.put("text", "DWA");
                                    }
                                    tagsArray.add(tag);
                                }
                            }
                        }
                    }
                    noteDTO.setUserTagList(tagsArray);
                }
            }
        }
        //帖子风味标签
        if (StringUtils.isNotEmpty(note.getTag())) {
            JSONArray list_tag = JSONArray.parseArray(note.getTag());
            noteDTO.setNoteTagList(list_tag);
        }
        return noteDTO;
    }

//    private String getDwaStudentTagByMobile(String mobile) {
//        String result = null;
//        String redisKey = "DwaStudentTag_" + mobile;
//        Object banners = redisUtils.get(redisKey);
//        if (banners != null && banners instanceof String) {
//            result = (String) banners;
//        }
//        if (result == null) {
//            synchronized (REDIS_LOCK2) {
//                List<Student> students = studentRepository.findAllByMobileOrderByLessonDesc(mobile);
//                if (null != students && students.size() > 0) {
//                    Student student = students.get(0);
//                    if (StringUtils.isNotEmpty(student.getLesson())) {
//                        String lesson = student.getLesson();
//                        result = "DWA L" + lesson.substring(lesson.length() - 1);
//                    }
//                } else {
//                    result = "";
//                }
//                redisUtils.set(redisKey, result, 300L);
//            }
//        }
//        return result;
//    }

    private List<String> getTeacherMobileList() {
        List<String> result = null;
        String redisKey = "TeacherMobileList";
        Object banners = redisUtils.get(redisKey);
        if (banners != null && banners instanceof List) {
            result = (List<String>) banners;
        }
        if (result == null) {
            synchronized (REDIS_LOCK3) {
                result = teacherRepository.findAllMobile();
                if (result == null) {
                    result = new ArrayList<>();
                }
                redisUtils.set(redisKey, result, 1200L);
            }
        }
        return result;
    }

    @Override
    public NoteDTO toDto(Note note) {
        NoteDTO result = null;
//        String redisKey = "NoteDto_" + note.getId();
//        Object banners = redisUtils.get(redisKey);
//        if (banners != null && banners instanceof NoteDTO) {
//            result = (NoteDTO) banners;
//        }
//        if (result == null) {
//            synchronized (REDIS_LOCK) {
                result = getDtoById(note);
//                redisUtils.set(redisKey, result, 60L);
//            }
//        }
        return result;
    }

    @Override
    public Note toEntity(NoteDTO noteDTO) {
        Note note = delegate.toEntity(noteDTO);
        Activity activity=noteDTO.getActivity();
        JSONArray list_tag = noteDTO.getNoteTagList();
        List<String> list_inviterId = new ArrayList<>();
        List<String> list_imgUrl = new ArrayList<>();
        if (noteDTO.getInviterList() != null){
            list_inviterId = noteDTO.getInviterList();
        }
        if (noteDTO.getImgUrlList() != null) {
            list_imgUrl = noteDTO.getImgUrlList();
        }
        if (list_imgUrl.size() > 0) {
            if (list_imgUrl.size() > 1) {
                note.setImgUrl(StringUtils.join(list_imgUrl, ","));
            }else {
                note.setImgUrl(list_imgUrl.get(0));
            }
        }
        if (null != list_tag && list_tag.size() > 0) {
            String tagStr = list_tag.toString();
            note.setTag(tagStr);
        }
        if (null != list_inviterId && list_inviterId.size() > 0) {
            note.setInviterId(StringUtils.join(list_inviterId, ","));
        }
        if(null != activity){
            note.setActivityId(activity.getId());
        }
        return note;
    }
}
